package cn.zgwj.org.service.impl;

import cn.zgwj.basic.service.impl.BaseServiceImpl;
import cn.zgwj.org.domain.Department;
import cn.zgwj.org.mapper.DepartmentMapper;
import cn.zgwj.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    //1.基础的CRUD的实现通过继承得到  BaseServiceImpl
    //但是如果有扩展业务,自己对应的基础实现
    @Override
    @Transactional
    public void add(Department department) {
        departmentMapper.save(department);//返回自增ID
        //需要保存dirPath
        String dirPath = "";
        if(department.getParent() == null){
            // 1.新增的是的顶级部门  /+我自己的id
            dirPath = "/"+department.getId();
        }else{
            //2.新增的不是顶级  需要查询出上级部门的dirPath + 自己的就可以了
            //根据父亲ID 查询出父亲的dirPath
            Department parentDept = departmentMapper.loadById(department.getParent().getId());
            //父亲的dirPath + 自己的
            dirPath = parentDept.getDirPath() + "/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    @Override
    @Transactional
    public void update(Department department) {
        //需要保存dirPath
        String dirPath = "";
        if(department.getParent() == null){
            // 1.新增的是的顶级部门  /+我自己的id
            dirPath = "/"+department.getId();
        }else{
            //2.新增的不是顶级  需要查询出上级部门的dirPath + 自己的就可以了
            //根据父亲ID 查询出父亲的dirPath
            Department parentDept = departmentMapper.loadById(department.getParent().getId());
            //父亲的dirPath + 自己的
            dirPath = parentDept.getDirPath() + "/"+department.getId();
        }
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }

    //2.扩展的接口实现自己写
    @Override
    public List<Department> findOneAndTwoLevelTree() {
        return departmentMapper.findOneAndTwoLevelTree();
    }
}
